package com.inhgroup.flashcards.io;

import com.inhgroup.flashcards.data.Card;
import com.inhgroup.flashcards.data.CardList;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.LinkedList;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Converts data from external data files to Card instances for this program.
 * 
 * @author Branden Ogata
 *
 */

public class CardReader
{
  /**
   * The logger for the CardReader class.
   * 
   */
  private static Logger logger = LoggerFactory.getLogger(CardReader.class.getName());
  
  /**
   * Returns the Card data within an Excel spreadsheet.
   * 
   * @param filename The String containing the name of the input file.
   * 
   * @return A CardList containing Cards created with the data from the input file.
   * 
   */
  
  public static CardList readExcelFile(String filename)
  {
    List<Card> cards = new LinkedList<Card>();
    CardList list = new CardList("", cards, "", "");
    
    try
    {
      Workbook workbook = WorkbookFactory.create(new FileInputStream(new File(filename)));
      Sheet sheet = workbook.getSheetAt(0);
      
      // First row should be the header indicating which languages are used
      String frontLanguage = sheet.getRow(0).getCell(0).getStringCellValue();
      String backLanguage = sheet.getRow(0).getCell(1).getStringCellValue();
      
      // Create a Card for each row after the first
      for (int i = 1; i < ExcelUtilities.getNumberOfRowsInSheet(sheet); i++)
      {
        try
        {
          Cell[] row = ExcelUtilities.getCellsInRow(sheet.getRow(i));
          cards.add(new Card(row[0].getStringCellValue(), row[1].getStringCellValue()));
        }
        catch (NullPointerException e)
        {
          logger.warn(String.format("Row %d has a null value.", i));
        }
      }
      
      list = new CardList(sheet.getSheetName(), cards, frontLanguage, backLanguage);
    }
    catch (IOException e)
    {
      logger.error(e.getMessage());
    }
    catch (InvalidFormatException e)
    {
      logger.error(e.getMessage());
    }
    catch (NullPointerException e)
    {
      logger.error(e.getMessage());
    }
    
    return list;
  }
}